<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Using Custom Element</title>
</head>
<body>
  <!-- 使用自定义元素 -->
  <custom-element>Hello Custom Element</custom-element>

  <script>
    // 从模板文件加载模板内容
    async function loadTemplate() {
      const response = await fetch('custom-element-template.html');
      const templateText = await response.text();
      return new DOMParser().parseFromString(templateText, 'text/html').querySelector('#custom-element-template');
    }

    // 定义自定义元素类
    class CustomElement extends HTMLElement {
      async connectedCallback() {
        // 创建 Shadow DOM
        const shadow = this.attachShadow({ mode: 'open' });

        // 获取模板内容
        const template = await loadTemplate();
        const templateContent = template.content;

        // 克隆模板内容并插入 Shadow DOM
        const clonedContent = templateContent.cloneNode(true);
        shadow.appendChild(clonedContent);

        // 获取按钮元素并添加事件监听器
        const button = shadow.querySelector('#custom-button');
        button.addEventListener('click', () => {
          console.log('Button clicked!');
        });
      }
    }

    // 注册自定义元素
    customElements.define('custom-element', CustomElement);
  </script>
</body>
</html>
